package com.lgx.group.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lgx.common.exception.DataException;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.mobile.entity.Group;
import com.lgx.mobile.entity.GroupChatRecord;
import com.lgx.mobile.service.IGroupChatRecordService;
import com.lgx.mobile.service.IGroupService;
import com.lgx.mobile.vo.GroupVO;
import com.lgx.right.entity.User;
import com.lgx.right.entity.UserExpand;
import com.lgx.right.service.IUserExpandService;
import com.lgx.right.vo.UserVO;

@Controller
@RequestMapping("/groupChat")  
public class GroupChatController {
	@Autowired
	IGroupService groupService;
	
	public IGroupService getGroupService() {
		return groupService;
	}
	
	@Autowired
	IGroupChatRecordService groupChatRecordService;

	public IGroupChatRecordService getGroupChatRecordService() {
		return groupChatRecordService;
	}

	@Autowired
	IUserExpandService userExpandService;

	public IUserExpandService getUserExpandService() {
		return userExpandService;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/groupChat.ftl")
	public String list(HttpServletRequest request,HttpServletResponse response){
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		
		request.setAttribute("basePath", basePath);
		
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		Object[] params = new Object[10];
		
		String groupId = request.getParameter("groupId");
		
		//获得圈子及创建者信息
		GroupVO groupVO = this.groupService.findGroupVOByGroupId(Long.parseLong(groupId));
		request.setAttribute("groupVO", groupVO);
		
		//获得圈子内所有聊天记录
		Pagination groupChatRecordPage = this.groupChatRecordService.findGroupChatRecordPaginationByGroupId(Long.parseLong(groupId), params, 5, Integer.parseInt(pageNum));
		request.setAttribute("groupChatRecordPage", groupChatRecordPage);
		
		request.setAttribute("pageNum", pageNum);
		
		//获取圈子内在线成员列表
		List<UserVO> onlineUserVOListInGroup = new ArrayList<UserVO>();
		Set<User> onlineUsers = (HashSet<User>) request.getSession().getAttribute(Constants.ONLINE_USER);//获得所有在线用户
		if(onlineUsers != null && onlineUsers.size() > 0){
			Object[] objOnlineUsers = onlineUsers.toArray();
			User onlineUser = new User();
			Group group = this.groupService.findGroupById(Long.parseLong(groupId));
			Set<User> users = group.getUsers();
			Object[] objUsers = users.toArray();
			UserExpand userExpand = new UserExpand();
			UserVO userVO = new UserVO();
			for(int i=0;i<objOnlineUsers.length;i++){
				onlineUser = (User)objOnlineUsers[i];
				for(int j=0;j<objUsers.length;j++){
					userExpand = this.userExpandService.findUserExpandByUserId(((User)objUsers[i]).getId());
					if(onlineUser.getId() == userExpand.getUser().getId()){
						userVO.setUserId(onlineUser.getId()+"");
						userVO.setUsername(onlineUser.getUsername());
						userVO.setNickname(onlineUser.getNickname());
						userVO.setTruename(onlineUser.getTruename());
						userVO.setEmail(onlineUser.getEmail());
						userVO.setSex(onlineUser.getSex());
						userVO.setMobile(onlineUser.getMobile());
						userVO.setCardId(onlineUser.getCard().getId());
						userVO.setDegree(userExpand.getDegree());
						userVO.setLevel(userExpand.getLevel());
						userVO.setHeadImage(userExpand.getHeadImage());
						userVO.setFunType(userExpand.getFunType());
						userVO.setGiftRecord(userExpand.getGiftRecord());
						userVO.setPoints(userExpand.getPoints());
						userVO.setPointRecordDate(userExpand.getPointRecordDate());
						onlineUserVOListInGroup.add(userVO);
					}
				}
			}
		}
		request.setAttribute("onlineUserVOListInGroup", onlineUserVOListInGroup);
		
		return "group/groupChat";
	}
	
	@RequestMapping("/index.htm")
	public String index(HttpServletRequest request,HttpServletResponse response){
		String groupId = request.getParameter("groupId");
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//得到当前登录人信息
		if(onlineUser != null){
			int n = 0;
			Group group = this.groupService.findGroupById(Long.parseLong(groupId));
			Object[] users = group.getUsers().toArray();
			for(int i=0;i<users.length;i++){
				if( ((User)users[i]).getId() == onlineUser.getId() ){
					n++;
				}
			}
			if(group.getCreateUserId() == onlineUser.getId()){
				n++;
			}
			if(n == 0){
				request.setAttribute("alertMsg", "您还没加入该圈子，请先加入！");
				return "group/group";
			}
		}else{
			request.setAttribute("alertMsg", "请先登录！");
			return "group/group";
		}
		return "group/groupChat";
	}
	
	@RequestMapping("/groupChatRecordSearch.htm")  
	public String userSearch(HttpServletRequest request,HttpServletResponse response) {
		String pageNum = request.getParameter("page");
		String groupId = request.getParameter("groupId");
		
		request.setAttribute("pageNum", pageNum);
		request.setAttribute("groupId", groupId);
		return "group/groupChat";
	}
	
	@RequestMapping("/publish.htm")
	public String Publish(HttpServletRequest request,HttpServletResponse response) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		request.setAttribute("basePath", basePath);
		
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//得到当前登录人信息
		//发表聊天内容
		String groupId = request.getParameter("groupId");
		String content = request.getParameter("content");
		
		GroupChatRecord groupChatRecord = new GroupChatRecord();
		groupChatRecord.setGroupId(Long.parseLong(groupId));
		groupChatRecord.setUserId(onlineUser.getId());
		groupChatRecord.setRecordDate(new Date());
		groupChatRecord.setContent(content);
		try {
			this.groupChatRecordService.createGroupChatRecord(groupChatRecord);
		} catch (DataException e) {
			e.printStackTrace();
			request.setAttribute("message", "发表失败！");
		}
		request.setAttribute("message", "发表成功！");
		
		try {
			response.sendRedirect(basePath + "groupChat/index.htm?groupId=" + groupId);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "group/groupChat";
	}
}
